package com.meisupic.copyright.controller;

import com.google.common.collect.Maps;
import com.meisupic.copyright.domain.vo.RealNameAuthVo;
import com.meisupic.copyright.domain.vo.VipMemberVo;
import com.meisupic.copyright.service.IAccountService;
import com.meisupic.copyright.service.VipMemberService;
import com.meisupic.copyright.support.Message;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/member")
public class VipMemberController extends BaseController {

  @Autowired
  private VipMemberService vipMemberService;

  @Autowired
  IAccountService accountService;

  @GetMapping("/getMemberCategory")
  public Message getMemberCategory() {
    return Message.success(vipMemberService.getMemberCategoryMap());
  }

  @PostMapping("/createOrder")
  public Message createOrder(Long memberCategoryId) {
    return Message.success(vipMemberService.createOrder(memberCategoryId, getUser()));
  }

  @GetMapping("/getAccountAuthType")
  public Message getAccountAuthType() {
    RealNameAuthVo realNameAuthVo = accountService.getRealNameAuthInfo(getUserId());
    if (realNameAuthVo != null) {
      return Message.success(realNameAuthVo.getAuthType());
    }
    return Message.success(null);
  }

  @GetMapping("/getEffectiveVipData")
  public Message getEffectiveVipData() {
    return Message.success(vipMemberService.getVipMember(getUserId()));
  }

  @GetMapping("/getAvailableServicesNum")
  public Message getAvailableServicesNum() {
    return Message.success(0);
  }

  @GetMapping("/getVipCategory")
  public Message getVipCategory() {
    Authentication authentication = SecurityContextHolder.getContext()
        .getAuthentication();
    if ("anonymousUser".equals(authentication.getPrincipal())) {
      try {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    Map result = Maps.newHashMap();
    RealNameAuthVo realNameAuthVo = accountService.getRealNameAuthInfo(getUserId());

    List<VipMemberVo> vipMemberVoList = vipMemberService.getVipMember(getUserId());

    List<Long> categoryIds = vipMemberVoList.stream().map(VipMemberVo::getMemberCategoryId)
        .collect(Collectors.toList());

    result.put("authType", realNameAuthVo == null ? "" : realNameAuthVo.getAuthType());
    result.put("categoryIds", categoryIds);

    return Message.success(result);
  }
}
